//
//  MYRegInfoViewController.m
//  投融保
//
//  Created by 523 on 13-12-17.
//  Copyright (c) 2013年 木叶科技. All rights reserved.
//

#import "MYRegInfoViewController.h"
#import "MYPersonalInfoViewController.h"
#import "MYCustomTextField.h"
#import "MYWebService.h"

#import "MYRegisterViewController.h"

#import "MYLoginViewController.h"

@interface MYRegInfoViewController ()

@end

extern  NSString *strMD5UserBaseId;
extern  NSString *registerName;
extern  NSString *appKey;
extern  NSString *key;

@implementation MYRegInfoViewController
{
    int isec;
    NSTimer *timer;
}

@synthesize scrollView;
@synthesize arrTextField;

@synthesize resendWebSerview;
@synthesize registerWebSerview;

@synthesize arrText;
@synthesize lblUserName;
@synthesize txtCaptcha;

@synthesize lblTitle;

@synthesize arrStr;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    //注册观察者，监听验证信息成功，接收注册信息
    //    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(verifiedSuccess) name:@"didgetDataAsyn" object:nil];
    
    
    SETBACKGROUND
    
    [self initView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)initView
{
    Y_=0;
    if (IOS_VERSION>=7.0) {
        Y_=20;
    }
    
    // 点击view用来关闭键盘
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(touchesBegan)];
    
    self.scrollView =[UIScrollView new];
    self.scrollView.frame=CGRectMake(0, Y_, SCREEN_HEIGHT, SCREEN_HEIGHT-Y_);
    [self.scrollView setShowsVerticalScrollIndicator:NO];
    self.scrollView=[UIScrollView new];
    [self.scrollView setFrame:CGRectMake(0, Y_, SCREEN_WIDTH,SCREEN_HEIGHT-Y_)];
    int scroll_y=260;
    if (SCREEN_HEIGHT>480) {
        scroll_y=180;
    }
    [self.scrollView setContentSize:CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT-Y_+scroll_y)];
    self.scrollView.scrollEnabled=YES;
    [self.scrollView addGestureRecognizer:tap];
    [self.view addSubview:self.scrollView];
    
    
    
    UIView *titleView=[[UIView alloc] initWithFrame:CGRectMake(0, Y_, SCREEN_WIDTH, 105)];
    [titleView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"titile_bg"]]];
    [self.view addSubview:titleView];
    
    lblTitle=[[UILabel alloc] initWithFrame:CGRectMake(250, 0, 268, 105)];
    [lblTitle setText:@"激活账户"];
    [lblTitle setTextColor:[UIColor whiteColor]];
    [lblTitle setFont:[UIFont boldSystemFontOfSize:40]];
    lblTitle.backgroundColor=[UIColor clearColor];
    lblTitle.textAlignment=NSTextAlignmentCenter;
    [titleView addSubview:lblTitle];
    
    UIButton *btnReturn=[UIButton new];
    [btnReturn setFrame:CGRectMake(0, 0, 105, 105)];
    [btnReturn setImage:[UIImage imageNamed:@"return_icon"] forState:UIControlStateNormal];
    [btnReturn.titleLabel setFont:[UIFont systemFontOfSize:11]];
    [btnReturn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnReturn addTarget:self action:@selector(btnReturnClick) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview: btnReturn];
    
    NSArray *arrPlaceHolder=[[NSArray alloc] initWithObjects:@"请设置登录密码",@"请再次输入登录密码",@"请设置支付密码",@"请再次输入支付密码",@"请输入手机号码", nil];
    
    float point_x=24;
    float point_y=105+40;
    float width=721;
    float height=105;
    
    self.lblUserName=[[UILabel alloc] initWithFrame:CGRectMake(point_x, point_y, width, height)];
    self.lblUserName.text=[NSString stringWithFormat:@"    %@",registerName];
    self.lblUserName.font=[UIFont systemFontOfSize:33];
    self.lblUserName.textColor=[UIColor darkGrayColor];
    [self.lblUserName.layer setCornerRadius:15.0];
    [self.lblUserName.layer setBorderWidth:1.0];
    [self.lblUserName.layer setBorderColor:[UIColor colorWithRed:218/255.0 green:218/255.0 blue:218/255.0 alpha:1.0].CGColor];
    
//    [self.lblUserName setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"lable_bg"]]];
    [self.lblUserName setBackgroundColor:[UIColor colorWithRed:234/255.0 green:234/255.0 blue:234/255.0 alpha:1.0]];
    [self.scrollView addSubview:lblUserName];
    //    lblUserName
    
    
    self.arrTextField =[NSMutableArray new];
    for (int i=0; i<=4; i++) {
        MYCustomTextField *text=[[MYCustomTextField alloc] initWithFrame:CGRectMake(point_x, point_y+(i+1)*(height+10), width, height)];
        text.tag=(10060+i);
        [text setPlaceholder:[arrPlaceHolder objectAtIndex:i]];
        [text setAutocorrectionType:UITextAutocorrectionTypeNo];
        [text setFont:[UIFont systemFontOfSize:33]];
        text.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        if (i<4) {
            text.secureTextEntry=YES;
        }
        text.delegate=self;
        [text setBackground:[UIImage imageNamed:@"textfild_bg"]];
        [text addTarget:self action:@selector(closekeyboard) forControlEvents:UIControlEventEditingDidEndOnExit];
        [arrTextField addObject:text];
        [self.arrText addObject:text];
        [self.scrollView addSubview:text];
    }
    
    txtCaptcha=[[MYCustomTextField alloc] initWithFrame:CGRectMake(point_x, point_y+6*(height+10), 350, height)];
    [txtCaptcha setPlaceholder:@"请输入验证码"];
    [txtCaptcha setFont:[UIFont systemFontOfSize:33]];
    [txtCaptcha setAutocorrectionType:UITextAutocorrectionTypeNo];
    txtCaptcha.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [txtCaptcha setBackground:[UIImage imageNamed:@"textfild_bg"]];
    [self.scrollView addSubview:txtCaptcha];
    
    UIButton *btnResend=[[UIButton alloc] initWithFrame:CGRectMake(point_x+370, point_y+6*(height+10), 350, height)];
    [btnResend setBackgroundImage:[UIImage imageNamed:@"login_bg"] forState:UIControlStateNormal];
    [btnResend setTitle:@"获取验证码" forState:UIControlStateNormal];
    [btnResend setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnResend.titleLabel setFont:[UIFont systemFontOfSize:40]];
    [btnResend addTarget:self action:@selector(btnResendCaptcha:) forControlEvents:UIControlEventTouchUpInside];
    [btnResend setTag:10065];
    [self.scrollView addSubview:btnResend];
    
    
    UIButton *btnConfirm=[UIButton new];
    [btnConfirm setFrame:CGRectMake(point_x, point_y+7*(height+10), width, height)];
    [btnConfirm setTitle:@"确认，下一步" forState:UIControlStateNormal ];
    [btnConfirm.titleLabel setFont:[UIFont systemFontOfSize:40]];
    [btnConfirm setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnConfirm setBackgroundImage:[UIImage imageNamed:@"login_bg"] forState:UIControlStateNormal];
    
    [btnConfirm addTarget:self action:@selector(btnConfirmClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:btnConfirm];
    
    //初始化保存输入框中数据的数组
    self.arrStr = [[NSMutableArray alloc] init];
    
}
//返回前页按钮方法
- (void)btnReturnClick
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (IBAction)btnConfirmClick:(UIButton *)sender
{
    
    [self.arrStr removeAllObjects];
    for(int i = 0; i <= 4; i++)
    {
        UITextField *tempText=(UITextField *)[self.view viewWithTag:10060+i];
        [self.arrStr addObject:tempText.text];
    }
    NSString *message;
    if (![arrStr[0] isEqualToString:arrStr[1]]) {
        message=@"登录密码不一致";
    }else if (![arrStr[2] isEqualToString:arrStr[3]])
    {
        message=@"支付密码不一致";
    }else
    {
        NSString *strAppUserActive=[NSString stringWithFormat:@"service=appUserActive&MD5UserBaseId=%@&verifyCode=%@&logPassword=%@&payPassword=%@&mobile=%@",strMD5UserBaseId,txtCaptcha.text,arrStr[0],arrStr[2],self.arrStr[4]];
        NSString *key=@"userInformations";
        //    NSString *strAppUserActive=@"service=appUserActive&MD5UserBaseId=d0159406087ff2da414ff3d8ebaf736a&verifyCode=060411&logPassword=111111&payPassword=111111";
        self.registerWebSerview =[MYWebService new];
        NSDictionary *resultDict=[self.registerWebSerview getDataSynWithKey:key encryptedString:strAppUserActive appKey:nil];
        NSLog(@"激活信息返回：%@",resultDict);
        
        if ([[[resultDict valueForKey:@"dataMap"] valueForKey:@"code" ] intValue]==1) {
            appKey=[resultDict valueForKey:@"appKey"];
            [self verifiedSuccess];
        }else
        {
            message=[[resultDict valueForKey:@"dataMap"] valueForKey:@"message"];
        }
    }
    
    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    if ([[[[self.registerWebSerview.profileDataSyn valueForKey:@"result"] valueForKey:@"dataMap"] valueForKey:@"code"] intValue]!=1) {
        [alert show];
    }
//#pragma mark- ---------仅供测试使用，用完删除
//    [self verifiedSuccess];
    
}



#pragma mark ------------------- 重发验证码
- (IBAction)btnResendCaptcha:(id)sender
{
    NSString *strphone=[(UITextField *)[self.view viewWithTag:10064] text];
    
    if (strphone&&[strphone stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length>0) {
        NSLog(@"--------------用户想重发验证码----------------------");
        
        NSString *strAppMobileService=[NSString stringWithFormat:@"service=appMobileService&mobile=%@&business=ACTIVATE",strphone];
        
        self.resendWebSerview=[MYWebService new];
        
        MBProgressHUD *mbHud = [[MBProgressHUD alloc] initWithView:self.view];
        mbHud.labelText = @"正在加载";
        [self.view addSubview:mbHud];
        mbHud.delegate = self;
        [mbHud showAnimated:YES whileExecutingBlock:^{
            //z菊花转动的时候 开始加载数据
            [self.resendWebSerview  getDataSynWithKey:key encryptedString:strAppMobileService appKey:nil];
        } completionBlock:^{
            //执行加载数据完成后的操作。
            
            NSDictionary *dict=[self.resendWebSerview.profileDataSyn objectForKey:@"result"];
            if ([[dict objectForKey:@"code"] intValue]==1) {
                isec=60;
                timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countdown:) userInfo:nil repeats:YES];
            }
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:[[self.resendWebSerview.profileDataSyn valueForKey:@"result"] valueForKey:@"message"] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
            
            
        }];
    }else{
        NSString *message=@"请输入手机号码";
        NSString *cancel=@"确定";
        ALERTVIEW(message, cancel);
    }
    

}

- (void)countdown:(NSTimer *)atimer
{
    isec--;
    [((UIButton *)[self.view viewWithTag:10065]) setTitle:[NSString stringWithFormat:@"获取验证码（%d）",isec] forState:UIControlStateNormal];
    if (isec<=0) {
        [timer invalidate];
        [((UIButton *)[self.view viewWithTag:10065]) setTitle:@"获取验证码（重发）" forState:UIControlStateNormal];
    }
    
}


// 点击view关闭键盘
- (void)touchesBegan
{
    [UIView animateWithDuration:0.25 animations:^{
        [self.scrollView setContentOffset:CGPointMake(0, 0)];
    }];
    [self.view endEditing:YES];
}

//接受验证成功通知
- (void)verifiedSuccess
{
    [self.scrollView removeFromSuperview];
    
    lblTitle.text=@"验证成功";
    
    
    UIView *viewVerifiedSuccess=[[UIView alloc] initWithFrame:CGRectMake(0, 105+Y_, SCREEN_WIDTH, SCREEN_HEIGHT-Y_)];
    [viewVerifiedSuccess setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:viewVerifiedSuccess];
    
    
    UIImageView *imageFace=[[UIImageView alloc] initWithFrame:CGRectMake(145, 113, 121, 121)];
    imageFace.image=[UIImage imageNamed:@"happyface"];
    [viewVerifiedSuccess addSubview:imageFace];
    
    UILabel *lblSuccess=[[UILabel alloc] initWithFrame:CGRectMake(280, 143, 400, 60)];
    lblSuccess.text=@"恭喜您！验证成功！";
    lblSuccess.textColor=UIColorFromRGB(0xb70100);
    lblSuccess.textAlignment=NSTextAlignmentLeft;
    lblSuccess.font=[UIFont systemFontOfSize:40];
    lblSuccess.backgroundColor=[UIColor clearColor];
    [viewVerifiedSuccess addSubview:lblSuccess];
    
    //直接登陆
    UIButton *btnLogin=[[UIButton alloc] initWithFrame:CGRectMake(84, 430, 290, 100)];
    [btnLogin setBackgroundImage:[UIImage imageNamed:@"login_bg"] forState:UIControlStateNormal];
    [btnLogin setTitle:@"直接登录" forState:UIControlStateNormal];
    [btnLogin setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnLogin.titleLabel setFont:[UIFont systemFontOfSize:40]];
    [btnLogin addTarget:self action:@selector(btnLoginAction:) forControlEvents:UIControlEventTouchUpInside];
    [viewVerifiedSuccess addSubview:btnLogin];
    //完善信息
    UIButton *btnInfo=[[UIButton alloc] initWithFrame:CGRectMake(394,430, 290, 100)];
    [btnInfo setBackgroundImage:[UIImage imageNamed:@"register_bg"] forState:UIControlStateNormal];
    [btnInfo setTitle:@"完善信息" forState:UIControlStateNormal];
    [btnInfo setTitleColor:UIColorFromRGB(0xb70100) forState:UIControlStateNormal];
    [btnInfo.titleLabel setFont:[UIFont systemFontOfSize:40]];
    [btnInfo addTarget:self action:@selector(btnInfoAction:) forControlEvents:UIControlEventTouchUpInside];
    [viewVerifiedSuccess addSubview:btnInfo];
    
    
    
}
//直接登陆
- (IBAction)btnLoginAction:(id)sender
{
//    [self presentModalViewController:[MYLoginViewController new] animated:YES];
    [self presentViewController:[MYLoginViewController new] animated:YES completion:nil];
    
}

//完善信息
-(IBAction)btnInfoAction:(id)sender
{
//    [self presentModalViewController:[MYPersonalInfoViewController new] animated:YES];
    [self presentViewController:[MYPersonalInfoViewController new] animated:YES completion:nil];
    
}


#pragma mark  ---------------text delegate---------------

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    //验证密码是否一致
}


- (void)closekeyboard
{
    [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    [self.view endEditing:YES];
}


#pragma mark-   -----------状态栏底色------
- (UIStatusBarStyle)preferredStatusBarStyle
{
    [self.view setBackgroundColor:[UIColor blackColor]];
    return UIStatusBarStyleLightContent;
}
- (BOOL)prefersStatusBarHidden
{
    return NO;
}
@end
